<?php
/**
 * Created by PhpStorm.
 * User: LFL
 * Date: 2010/5/25
 * Time: 16:02
 */
namespace api\controllers;

use common\service\ShopService;
use common\service\WarehouseService;
use Yii;
use yii\web\Controller;
use backend\models\GoodsCategory;
use common\helps\tools;

class CommController extends Controller
{
    //仓库列表
    public function actionGetCategory()
    {
        $returnArr = array();
        //一级分类列表
        $where = ['use_flg' => 1, 'level' => 1];
        $returnArr['bigCategory'] = GoodsCategory::find()->where($where)->orderBy('sort')->asArray()->all();

        //二级分类列表
        $midCategory = array();
        $where = ['use_flg' => 1, 'level' => 2];
        $result = GoodsCategory::find()->where($where)->orderBy('sort')->asArray()->all();
        foreach ($result as $value) {
            $midCategory[$value['parent_id']][] = $value;
        }
        $returnArr['midCategory'] = $midCategory;

        //三级分类列表
        $smallCategory = array();
        $where = ['use_flg' => 1, 'level' => 3];
        $result = GoodsCategory::find()->where($where)->orderBy('sort')->asArray()->all();
        foreach ($result as $value) {
            $smallCategory[$value['parent_id']][] = $value;
        }
        $returnArr['smallCategory'] = $smallCategory;

        $this->retJson('', 200, $returnArr);
    }

    //获取门店信息
    public function actionGetWarehouse()
    {
        $sql = 'SELECT id,warehouseName FROM j_warehouse WHERE useFlg=1 AND can_Frozen=1';
        $res = Yii::$app->db->createCommand($sql)->queryAll();
        $this->retJson('', 200, $res);
    }




    public function actionGetWarehouses()
    {
        $shops = Yii::$app->request->post();
        $shopIds = array_column($shops, 'shopId');

        if (in_array(0, $shopIds)) {
            $shops = ShopService::findAll();
        } else {
            $shops = ShopService::findShopByIds($shopIds);
        }


        $shopIds = array_column($shops, 'ShopID');


        $warehouseIds = [];

        $ws_groups = ShopService::findWarehouseShopGroupAll();


        if ($ws_groups) {
            foreach ($ws_groups as $group) {
                if ($group['shopIds'] != '' && $group['warehouseIds'] != '') {
                    $g_shopIds = explode(',', $group['shopIds']);
                    $g_warehouseIds = explode(',', $group['warehouseIds']);

                    if (in_array(0, $g_shopIds)) {
                        $warehouseIds = array_merge($warehouseIds, $g_warehouseIds);
                    } else {
                        if (array_intersect($g_shopIds, $shopIds)) {
                            $warehouseIds = array_merge($warehouseIds, $g_warehouseIds);
                        }
                    }
                }
            }
        }

        if ($warehouseIds) {
            if (in_array(0, $warehouseIds)) {

                $result = WarehouseService::findAll();
                $this->retJson('', 200, $result);

            } else {
                $result = WarehouseService::findWarehouseByIds($warehouseIds);
                $this->retJson('', 200, $result);
            }
        }

    }


    public function actionGetWarehousesByShopId()
    {
        $data = Yii::$app->request->post();
        $shopId = $data['shopId'];

        if ($shopId == 0) {
            $shops = ShopService::findAll();
        } else {
            $shops = ShopService::findShopByIds($shopId);
        }


        $shopIds = array_column($shops, 'ShopID');


        $warehouseIds = [];

        $ws_groups = ShopService::findWarehouseShopGroupAll();


        if ($ws_groups) {
            foreach ($ws_groups as $group) {
                if ($group['shopIds'] != '' && $group['warehouseIds'] != '') {
                    $g_shopIds = explode(',', $group['shopIds']);
                    $g_warehouseIds = explode(',', $group['warehouseIds']);

                    if (in_array(0, $g_shopIds)) {
                        $warehouseIds = array_merge($warehouseIds, $g_warehouseIds);
                    } else {
                        if (array_intersect($g_shopIds, $shopIds)) {
                            $warehouseIds = array_merge($warehouseIds, $g_warehouseIds);
                        }
                    }
                }
            }
        }

        if ($warehouseIds) {
            if (in_array(0, $warehouseIds)) {

                $result = WarehouseService::findAll();
                $this->retJson('', 200, $result);

            } else {
                $result = WarehouseService::findWarehouseByIds($warehouseIds);
                $this->retJson('', 200, $result);
            }
        }

    }



    //获取门店信息
    public function actionGetShop()
    {

        $data = Yii::$app->request->post();
        $sql = 'SELECT ShopID,ShopName,Address,shopType FROM j_shop';
        if(isset($data['shopId']) && !empty($data['shopId'])) {
            $sql .= ' WHERE ShopID IN(' . $data['shopId'] . ')';
        }
        $res = Yii::$app->db->createCommand($sql)->queryAll();
        $this->retJson('', 200, $res);
    }

    //upload
    public function actionPicUpload()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        try {
            $fileExt = Yii::$app->request->post('fileExt', 'png');
            $path = $this::mkFile('materiel', $fileExt);
            //文件夹创建权限
            if (!tools::arrayHasValue($path, 'bathurl') || !tools::arrayHasValue($path, 'hostUrl')) {
                throw new \Exception('没有创建文件夹权限', 1001);
            }

            //临时文件处理
            if (!tools::arrayHasValue($_FILES, 'material')) {
                throw new \Exception('临时文件未找到', 1002);
            }

            //移动文件
            if (!move_uploaded_file($_FILES["material"]["tmp_name"], $path['bathurl'])) {
                throw new \Exception('未知错误');
            }

            return [
                'data' => $path,
                'code' => 200,
                'msg' => '上传图片成功'
            ];


        } catch (\Exception $e) {
            elog($e->getMessage());

            return [
                'data' => [],
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
            ];
        }
    }

    //生成文件路径
    public static function mkFile($dirPath ,$fileExt)
    {
        $base_path = Yii::$app->params['IMG_UPLOAD_PATH'];
        $randName = time() . rand(1000, 99999) . "." . $fileExt; //重新编译文件名称
        $path = date('Y-m-d', time());
        $bath_path = $base_path . $dirPath . '/' . $path;
        if (!file_exists($bath_path)) {   //判断该目录是否存在
            mkdir($bath_path, 0777, true);
        }

        return [
            'bathurl' => $base_path . $dirPath . '/' . $path . '/' . $randName,
            'hostUrl' => $dirPath . '/' . $path . '/' . $randName
        ];
    }
}